package com.whpost.service.service.t;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.dao.t.TRegionDao;
import com.whpost.service.entity.t.TCzy;
import com.whpost.service.entity.t.TRegion;
import com.whpost.service.entity.t.TXzjg;
import com.whpost.service.entity.t.TreeNode;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.tools.ToolBean;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TRegionServices extends BaseServices<TRegionDao, TRegion> {

    @Resource
    private TApiNonceService tApiNonceService;

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String curpage = "",pagesize="",cxmc="";
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("cxmc")) {
                cxmc = jsonObject.getString("cxmc");
            }

            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "10";

            Page<TRegion> page = new Page<>( Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<TRegion> TRegionListInfo = new ListInfo<>();
            QueryWrapper<TRegion> tRegionQueryWrapper = new QueryWrapper<TRegion>();
            if (!StringUtils.isEmpty(cxmc)){
                tRegionQueryWrapper.like("name",cxmc);
            }else{
                tRegionQueryWrapper.eq("1","1");
            }
            tRegionQueryWrapper.orderByAsc("xh");

            IPage<TRegion> TRegionIPage = getBaseMapper().selectPage(page,tRegionQueryWrapper);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(TRegionIPage.getTotal());
            pageInfo.setCurPage(TRegionIPage.getCurrent());
            pageInfo.setPageSize(TRegionIPage.getSize());
            pageInfo.setPageTotal(TRegionIPage.getPages());

            TRegionListInfo.setPageInfo(pageInfo);
            TRegionListInfo.setListInfo(TRegionIPage.getRecords());

            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",TRegionListInfo);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo tree(String loginId,Map<String, Object> map) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            Map<String,Object> rtnMap = new HashMap<>();
            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            TRegion tRegion = new TRegion();
            TRegion tRegionSon = new TRegion();
            String treejson="";
            //一级菜单
            List<TRegion> tRegionList = new ArrayList<>();
            tRegionList = getBaseMapper().selectList(new QueryWrapper<TRegion>().eq("jb","1").orderByAsc("xh"));

            //二级菜单
            List<TRegion> tRegionListSon = new ArrayList<>();
            for (int i=0;i<tRegionList.size();i++){
                tRegion = new TRegion();
                tRegion = tRegionList.get(i);
                treejson += "{id:\""+tRegion.getId()+"\",name: \""+tRegion.getName()+"\",dz:\"info?lx=1&id="+tRegion.getId()+"\",open: false},";
                //放入二级菜单
                tRegionListSon = new ArrayList<>();
                tRegionListSon = getBaseMapper().getRegionXjNoRoot(tRegion.getId());
                for (int k=0;k<tRegionListSon.size();k++){
                    tRegionSon = new TRegion();
                    tRegionSon = tRegionListSon.get(k);
                    treejson += "{id:\""+tRegionSon.getId()+"\",pId:\""+tRegionSon.getPid()+"\", name: \""+tRegionSon.getName()+"\",dz:\"info?lx=1&id="+tRegionSon.getId()+"\",open: false},";
                }
            }
            rtnMap.put("treejson", JSON.parse("["+treejson+"]"));
            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",rtnMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo info(String loginId, Map<String, Object> map){
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String lx="",id="",pid="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("pid")) {
                pid = jsonObject.getString("pid");
            }
            Map<String,Object> rtnMap = new HashMap<>();

            if ("1".equals(lx)){
                TRegion tRegion = new TRegion();
                tRegion = getBaseMapper().getRegionById(id);
                rtnMap.put("tRegion",tRegion);

                //小于或者等于它自己级别的，又不是它自己的可以
                QueryWrapper<TRegion> tRegionQueryWrapper = new QueryWrapper<TRegion>();
                tRegionQueryWrapper.le("jb",tRegion.getJb()).ne("id",tRegion.getId());
                if (null!=tRegion.getPid()) tRegionQueryWrapper.ne("id",tRegion.getPid());
                List<TreeNode> qyjgTree = getTreeSelect(tRegionQueryWrapper);   //禁用父节点
                rtnMap.put("qyjgTree",qyjgTree);
            }
            if (!StringUtils.isEmpty(pid)){
                TRegion pRegion = new TRegion();
                pRegion = getBaseMapper().getRegionById(pid);
                if (null==pRegion){
                    return new ResultInfo(500,"上级机构信息丢失！",null);
                }
                rtnMap.put("pRegion",pRegion);
            }

            ResultInfo resultInfo = new ResultInfo(0, "查询成功！",rtnMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo save(String loginId, Map<String, Object> map) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            JSONObject jsonObject = getData(map,loginId);
            String lx="",id="",nonce_ms="",nonce_zhi="",jgmc="",jgh="",xsxh="",pid="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("jgmc")) {
                jgmc = jsonObject.getString("jgmc");
            }
            if (jsonObject.containsKey("jgh")) {
                jgh = jsonObject.getString("jgh");
            }
            if (jsonObject.containsKey("xsxh")) {
                xsxh = jsonObject.getString("xsxh");
            }
            if (jsonObject.containsKey("pid")) {
                pid = jsonObject.getString("pid");
            }

            if (StringUtils.isEmpty(jgmc)){
                ResultInfo resultInfo = new ResultInfo(500, "名称不能为空！",null);
                return backRtn(resultInfo,loginId);
            }

            if (jsonObject.containsKey("nonce_ms")) {
                nonce_ms = jsonObject.getString("nonce_ms");
            }
            if (jsonObject.containsKey("nonce_zhi")) {
                nonce_zhi = jsonObject.getString("nonce_zhi");
            }

            //校验nonce
            ResultInfo ResultInfoCheckNonce = new ResultInfo();
            ResultInfoCheckNonce = tApiNonceService.checkNonce(nonce_ms,loginId,nonce_zhi,"region.addDo");

            if (ResultInfoCheckNonce.getCode()!=200)
            {
                return ResultInfoCheckNonce;
            }

            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            TRegion tRegion = new TRegion();
            TRegion pRegion = new TRegion();
            if ("1".equals(lx)){
                tRegion = getBaseMapper().selectById(id);
            }
            tRegion.setName(jgmc);
            tRegion.setZjm(ToolBean.getPy(jgmc));

            if (!StringUtils.isEmpty(pid)){
                pRegion = getBaseMapper().selectById(pid);
            }

            //如果有上级，级别为上级的级别+1
            if (!StringUtils.isEmpty(pid)){
                tRegion.setPid(Long.valueOf(pid));
                tRegion.setJb(pRegion.getJb()+1);
            }else{
                //如果是修改，不改变级别，如果是新增，则都是第一级
                if ("0".equals(lx)) tRegion.setJb(1L);
            }

            if (!StringUtils.isEmpty(xsxh)) tRegion.setXh(Long.valueOf(xsxh));
            ResultInfo resultInfo;
            Map<String,Object> rtnMap = new HashMap<>();
            rtnMap.put("name",jgmc);
            if ("1".equals(lx)){
                getBaseMapper().updateById(tRegion);
                resultInfo = new ResultInfo(2, "修改成功！",rtnMap);
            }else{
                getBaseMapper().insert(tRegion);
                resultInfo = new ResultInfo(1, "新增成功！",rtnMap);
            }
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo qy(String loginId, Map<String, Object> map) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            JSONObject jsonObject = getData(map,loginId);
            String id="",new_pid="";
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("new_pid")) {
                new_pid = jsonObject.getString("new_pid");
            }

            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            TRegion tRegion;
            TRegion tRegion1;
            tRegion = getBaseMapper().selectById(id);
            tRegion1 = getBaseMapper().selectById(new_pid);

            if (StringUtils.isEmpty(id) || null==tRegion){
                ResultInfo resultInfo = new ResultInfo(500, "关键参数丢失！",null);
                return backRtn(resultInfo,loginId);
            }

            if (id.equals(new_pid)){
                ResultInfo resultInfo = new ResultInfo(500, "新上级不能选择自己！",null);
                return backRtn(resultInfo,loginId);
            }
            if (StringUtils.isEmpty(new_pid) || null==tRegion1){
                getBaseMapper().setPidNull(tRegion.getId());
            }else{
                tRegion.setPid(Long.parseLong(new_pid));
                tRegion.setJb(tRegion1.getJb()+1);
                //更新自己的级别和父节点
                getBaseMapper().updateById(tRegion);
            }
            //更新儿子们的级别
            getBaseMapper().updateJb(tRegion.getId());


            Map<String,Object> rtnMap = new HashMap<>();
            rtnMap.put("name",tRegion.getName());
            return backRtn(new ResultInfo(1, "迁移成功！",rtnMap),loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo del(String loginId, Map<String, Object> map) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            JSONObject jsonObject = getData(map,loginId);
            String menu_id="";
            if (jsonObject.containsKey("id")) {
                menu_id = jsonObject.getString("id");
            }
            if (StringUtils.isEmpty(menu_id)){
                ResultInfo resultInfo = new ResultInfo(500, "没有需要删除的信息！",null);
                return backRtn(resultInfo,loginId);
            }
            long sl = getBaseMapper().selectCount(new QueryWrapper<TRegion>().eq("pid",menu_id.trim()));
            if (sl>=1){
                ResultInfo resultInfo = new ResultInfo(500, "请先删除下级数据！",null);
                return backRtn(resultInfo,loginId);
            }else {
                getBaseMapper().deleteById(menu_id);
                ResultInfo resultInfo = new ResultInfo(3, "删除成功！",null);
                return backRtn(resultInfo,loginId);
            }
        }
    }

    public List<TreeNode> getTreeSelect(){
        List<TRegion> allCpflList = baseMapper.selectList(null);
        Map<Long, TreeNode> nodeMap = new HashMap<>();
        List<TreeNode> rootNodes = new ArrayList<>();

        // 1. 初始化所有节点，使用 value 而非 id
        for (TRegion cpfl : allCpflList) {
            TreeNode node = new TreeNode();
            node.setValue(cpfl.getId());  // 将实体的 id 映射为节点的 value
            node.setName(cpfl.getName());
            node.setDisabled("0".equals(cpfl.getState()));
            node.setSelected(false);
            nodeMap.put(cpfl.getId(), node);
        }

        // 2. 构建父子关系
        for (TRegion cpfl : allCpflList) {
            TreeNode currentNode = nodeMap.get(cpfl.getId());
            Long parentId = cpfl.getPid();

            if (parentId == null || !nodeMap.containsKey(parentId)) {
                rootNodes.add(currentNode);
            } else {
                TreeNode parentNode = nodeMap.get(parentId);
                parentNode.getChildren().add(currentNode);
            }
        }

        // 3. 设置特殊节点状态
        List<TreeNode> rtn = setExampleSpecialNodes(rootNodes);

        return rtn;
    }

    public List<TreeNode> getTreeSelect(QueryWrapper<TRegion> tRegionQueryWrapper){
        List<TRegion> allCpflList = baseMapper.selectList(tRegionQueryWrapper);
        Map<Long, TreeNode> nodeMap = new HashMap<>();
        List<TreeNode> rootNodes = new ArrayList<>();

        // 1. 初始化所有节点，使用 value 而非 id
        for (TRegion cpfl : allCpflList) {
            TreeNode node = new TreeNode();
            node.setValue(cpfl.getId());  // 将实体的 id 映射为节点的 value
            node.setName(cpfl.getName());
            node.setDisabled("0".equals(cpfl.getState()));
            node.setSelected(false);
            nodeMap.put(cpfl.getId(), node);
        }

        // 2. 构建父子关系
        for (TRegion cpfl : allCpflList) {
            TreeNode currentNode = nodeMap.get(cpfl.getId());
            Long parentId = cpfl.getPid();

            if (parentId == null || !nodeMap.containsKey(parentId)) {
                rootNodes.add(currentNode);
            } else {
                TreeNode parentNode = nodeMap.get(parentId);
                parentNode.getChildren().add(currentNode);
            }
        }

        // 3. 设置特殊节点状态
        List<TreeNode> rtn = setExampleSpecialNodes(rootNodes);

        return rtn;
    }
}
